package club.easin.config.db;

import club.easin.enums.DbEmHelper;

import java.util.Optional;
import java.util.concurrent.atomic.AtomicInteger;

public class DbContextHolder {

    private static ThreadLocal<Optional<DbEmHelper.DbTypeEm>> dbTypeEmThreadLocal=new ThreadLocal<>();

    private static  final AtomicInteger atoCounter=new AtomicInteger(0);

    public static  void setDb(DbEmHelper.DbTypeEm dbTypeEm){
        dbTypeEmThreadLocal.set(Optional.ofNullable(dbTypeEm));
    }

    public static Optional<DbEmHelper.DbTypeEm> getDb(){
        return dbTypeEmThreadLocal.get();
    }

    public static  void remove(){
        dbTypeEmThreadLocal.remove();
    }
    /**
     * 设置主库
     */

    public static void setDb(boolean isMaster){
        if(isMaster){
            setDb(DbEmHelper.DbTypeEm.db0);
        }else if(DbEmHelper.DbTypeEm.values().length==1){
            setDb(DbEmHelper.DbTypeEm.db0);
        } else{
            setSlave();
        }
    }

    private static  void setSlave(){
        if(atoCounter.get()>=100000){
            atoCounter.set(0);
        }
        int slavNum=atoCounter.getAndIncrement()%(DbEmHelper.DbTypeEm.values().length-1);
        Optional<DbEmHelper.DbTypeEm> dbTypeEm=DbEmHelper.DbTypeEm.getDbTypeBySlaveNum(slavNum);
        if(dbTypeEm.isPresent()){
            setDb(dbTypeEm.get());
        }else {
            throw new  IllegalArgumentException("从库未匹配");
        }
    }
}
